package com.leyou.search.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.bo.SpuBo;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.SpecParam;
import com.leyou.item.pojo.Spu;
import com.leyou.item.pojo.SpuDetail;
import com.leyou.search.client.CategoryClient;
import com.leyou.search.client.GoodsClient;
import com.leyou.search.client.SpecClient;
import com.leyou.search.pojo.Goods;
import com.leyou.search.repository.GoodsRepository;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Author: Saka
 * Date: 2019/2/1
 * Time: 19:03
 */
@Service
public class IndexService {
    @Autowired
    private GoodsClient goodsClient;
    @Autowired
    private CategoryClient categoryClient;
    @Autowired
    private SpecClient specClient;

    @Autowired
    private GoodsRepository goodsRepository;

    public Goods buildGoods(SpuBo spu) {
        Goods goods = new Goods();
        //对应属性拷贝值
        BeanUtils.copyProperties(spu, goods);

        List<String> names = this.categoryClient.queryNameByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));


        //  all：用来进行全文检索的字段，里面包含标题、商品分类信息
        goods.setAll(spu.getTitle()+ " "+StringUtils.join(names," "));

        //goods.setSkus();
        // price：价格数组，是所有sku的价格集合。方便根据价格进行筛选过滤
        //goods.setPrice();
        List<Sku> skus = this.goodsClient.querySkuBySpuId(spu.getId());
        List<Long> prices = new ArrayList<>();
        List<Map<String, Object>> skuList = new ArrayList<>();

        skus.forEach(sku -> {
            prices.add(sku.getPrice());
            Map<String, Object> skuMap = new HashMap<>();
            skuMap.put("id", sku.getId());
            skuMap.put("title", sku.getTitle());
            skuMap.put("image", sku.getImages());
            skuMap.put("price", sku.getPrice());
            skuList.add(skuMap);

        });
        goods.setPrice(prices);

        //  skus：用于页面展示的sku信息，不索引，不搜索。包含skuId、image、price、title字段
        goods.setSkus(JsonUtils.serialize(skuList));

        //     specs：所有可搜索规格参数的集合。key是参数名，值是参数值。
        //首先要根据分类查询规格参数并筛选出规格参数中的可搜索部分

        //获取sup详情信息
        SpuDetail spuDetail = this.goodsClient.querySpuDetailById(spu.getId());

        String genericSpec = spuDetail.getGenericSpec();
        //通用的规格参数值
        Map<Long, Object> genericSpecMap = JsonUtils.parseMap(genericSpec, Long.class, Object.class);

        String specialSpec = spuDetail.getSpecialSpec();
        //特有的规格参数值
        Map<Long, List<String>> specialSpecMap = JsonUtils.nativeRead(specialSpec, new TypeReference<Map<Long, List<String>>>() {
        });

        //查询分类对应的规格参数
        List<SpecParam> params = this.specClient.querySpecParam(null, spu.getCid3(), null, true);

        //处理规格参数显示问题,默认显示id值,处理后显示id对应的名称值
        Map<String, Object> specs = new HashMap<>();
        for (SpecParam param : params) {
                Long paramId = param.getId();
                String name = param.getName();
                //通用参数
                Object value = null;
                if (param.getGeneric()) {
                    //通用参数
                    value = genericSpecMap.get(paramId);

                    if (param.getNumeric()) {
                        //数值类型需要加分段
                        value = this.chooseSegment(value.toString(), param);

                    }


                }  else {//特有参数
                    value = specialSpecMap.get(paramId);

                }
                if (null == value) {
                    value = "其他";
                }
                specs.put(name, value);
        }


        goods.setSpecs(specs);

        return goods;




    }

    private String chooseSegment(String value, SpecParam p) {
        double val = NumberUtils.toDouble(value);
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = NumberUtils.toDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if(segs.length == 2){
                end = NumberUtils.toDouble(segs[1]);
            }
            // 判断是否在范围内
            if(val >= begin && val < end){
                if(segs.length == 1){
                    result = segs[0] + p.getUnit() + "以上";
                }else if(begin == 0){
                    result = segs[1] + p.getUnit() + "以下";
                }else{
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    public void createIndex(Long id){
        Spu spu = this.goodsClient.querySpuById(id);
        SpuBo spuBo = new SpuBo();
        BeanUtils.copyProperties(spu,spuBo);
        Goods goods = this.buildGoods(spuBo);
        this.goodsRepository.save(goods);
    }

    public void deleteIndex(Long id) {
        this.goodsRepository.deleteById(id);
    }
}
